package com.cloudkinto.session;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Transactional(rollbackFor = Exception.class)//事务回滚
@Service
public class UserSessionRepositoryImpl implements UserSessionRepository {

    private final static Logger logger = LoggerFactory.getLogger(UserSessionRepositoryImpl.class);
    private static String SESSION_PREX = "USER_SESSION_TOKEN:";
    @Value("${server.servlet.session.timeout}")
    private int sessionMaxTime;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserSession querySession(String sessionId) {
        try {
            if (null != redisTemplate.opsForValue().get(SESSION_PREX + sessionId)) {
                String jsonString = (String) redisTemplate.opsForValue().get(SESSION_PREX + sessionId);
                UserSession userSession = JSON.parseObject(jsonString, UserSession.class);
                // 刷新下当前下缓存,重置过期时间
                redisTemplate.expire(SESSION_PREX + userSession.getSessionId(), sessionMaxTime, TimeUnit.SECONDS);//设置超时时间
                return userSession;
            }
        } catch (Exception ex) {
            logger.error("获取缓存对象失败", ex);
        }
        return null;
    }

    @Override
    public UserSession saveSession(UserSession session) {
        try {
            if (null != session && StringUtils.isNotBlank(session.getSessionId())) {
                redisTemplate.opsForValue().set(SESSION_PREX + session.getSessionId(), JSONObject.toJSONString(session), sessionMaxTime, TimeUnit.SECONDS);
            }
        } catch (Exception ex) {
            logger.error("生成缓存对象失败", ex);
        }
        return null;
    }

    @Override
    public void removeSession(String sessionId) {
        try {
            if (StringUtils.isNotBlank(sessionId)) {
                if (redisTemplate.opsForValue().get(SESSION_PREX + sessionId) != null) {
                    redisTemplate.delete(SESSION_PREX + sessionId);
                }
            }
        } catch (Exception ex) {
            logger.error("删除缓存对象失败", ex);
        }
    }
}
